package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.service.CartService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Iterator;

public class CartFormServlet extends HttpServlet {
    private static  final  String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("loginAccount");
        if(account != null){
            CartService cartService = new CartService();
            Iterator<CartItem> cartItems = cartService.getCartItems(account.getUsername());
            int numberOfItems = cartService.getNumberOfItems(account.getUsername());
            BigDecimal subTotal = cartService.getSubTotal(account.getUsername());
            session.setAttribute("cartItems",cartItems);
            session.setAttribute("numberOfItems",numberOfItems);
            session.setAttribute("subTotal",subTotal);
            req.getRequestDispatcher(CART_FORM).forward(req,resp);
        }else{
            resp.sendRedirect("signonForm");
        }

    }
}
